import { onUnmounted } from "vue";

//封装节流函数hook
export const useThrottle = (fn: Function, delay: number) => {
    let timeoutId:any;
    let lastArgs:any;

    const throttledFn = (...args) => {
        lastArgs = args;

        if (!timeoutId) {
            timeoutId = setTimeout(() => {
                fn(...lastArgs);
                lastArgs = null;
                timeoutId = null;
            }, delay);
        }
    };

    // 清理定时器
    onUnmounted(() => {
        if (timeoutId) {
            clearTimeout(timeoutId);
        }
    });

    return throttledFn;
};